package com.ylt.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.utils.MD5UtilSecurity;
import com.utils.WeixinServlet;
import com.utils.redis.RedisUtil;
import com.utils.tfzf.Kv;
import com.utils.ylt.PkeyGenerator;
import com.utils.ylt.SignUtil;
import com.utils.ylt.SignUtils;
import com.utils.ylt.SwiftpassConfig;
import com.utils.ylt.XmlUtils;
import com.utils.ylt.YltUtils;
import com.ylt.controller.pay.JSSDK_Config;
import com.ylt.controller.pay.WxPayHandle;
import com.ylt.controller.pay.XcxPay;
import com.ylt.dao.mysqldb.ShopChatDao;
import com.ylt.dao.oracledb.WeChatDao;
import com.ylt.service.WeChatService;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.swagger.annotations.Api;


/**
 * @author zhouliang
 * @create 2018-12-03 18:07
 * 小程序接口
 */
@Controller
@RequestMapping( "/ylt")
@Api(tags = "微信小程序接口")
public class WeChatController {

    @Autowired
    WeChatService weChatService;
    @Autowired
    WeChatDao weChatDao;
    @Autowired
    ShopChatDao shopChatDao;
    @Autowired
    WxPayHandle wxHandle;

    @Autowired
    private RedisUtil redisUtil;

    InternalLogger log = Log4JLoggerFactory.getInstance(WeChatController.class);

    /**
     * 首页轮播banner接口（参数：无）
     * @param shopId
     * @return
     */
    @RequestMapping("/shop_image")
    @ResponseBody
    public Object getImageInfo(@RequestParam(name = "shopId",required = false,defaultValue = "1") String shopId) {
        Map returnMap = new HashMap();
        try {
            List imageInfo= weChatService.getImageInfo(shopId);
            returnMap.put("data", imageInfo);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");

        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    /**
     * 首页行业新闻接口（参数：无）
     * @param map
     * @return
     */
    @RequestMapping("/news")
    @ResponseBody
    public Object getYlt_news(@RequestParam(required = false) Map map) {

        Map returnMap = null;
        try {
            List news= weChatService.getYlt_news();
            returnMap = new HashMap();
            returnMap.put("data",news);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    /**
     * 微信绑定接口
     * @param wx_id
     * @param u_account
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping("/binging_wx")
    public Object binging_wx(@RequestParam(name ="wx_id" , required = false) String wx_id,@RequestParam(name ="u_account", required = true) String u_account,
                             @RequestParam(name ="u_password", required = true) String password) {

        Map returnMap = new HashMap();
        try {
            Map checkMap = new HashMap();
            String u_password = YltUtils.md5Digest(password);
            checkMap.put("U_PASSWORD",u_password);
            checkMap.put("U_ACCOUNT",u_account);
            checkMap.put("WX_ID",wx_id);
            Integer count = weChatService.binging_wx_check(checkMap);
            if (count<=0) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "未找到用户信息,请检查用户名密码是否正确");
                return  returnMap;
            }


            if (wx_id==null || wx_id.isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "微信号未传入");
                return  returnMap;
            }
            // 绑定微信
            weChatService.binging_wx(checkMap);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    /**
     * 客户信息接口
     * @param wx_id
     * @return
     */
    @ResponseBody
    @RequestMapping("/getYlt_customerInfo")
    public Object getYlt_customerInfo(@RequestParam(name ="wx_id" , required = false) String wx_id) {

        Map returnMap = new HashMap();
        try {
            if (wx_id==null || wx_id.isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "微信号未传入");
                return  returnMap;
            }
            // 绑定微信
            Map tempList = weChatService.getYlt_customerInfo(wx_id);
            returnMap.put("data",tempList);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }


    @ResponseBody
    @RequestMapping("/getYlt_orders_header")
    public Object getYlt_orders_header(@RequestParam(name ="cust_id" , required = false) String cust_id,
                                       @RequestParam(required = false,name = "ordertype") String so_zt,
                                       @RequestParam(required = false,name = "pay_state") String pay_state,
                                       @RequestParam(name = "pageNum",required =true ) Integer pageNum,
                                       @RequestParam(name = "pageSize",required = true) Integer pageSize) {

        Map returnMap = new HashMap();
        try {
            if (cust_id==null || cust_id.isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "客户未传入");
                return  returnMap;
            }
            if (pageNum==null || pageSize==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "无分页信息");
                return  returnMap;
            }
            PageInfo orders = weChatService.getYlt_orders_header(pageNum,pageSize,cust_id,so_zt,pay_state);
            returnMap.put("data",orders);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    @ResponseBody
    @RequestMapping("/getYlt_orders_line")
    public Object getYlt_orders_LINE(@RequestParam(name ="b2b_order_number" , required = true) String b2b_order_number,
                                     @RequestParam(name = "pageNum",required =true ) Integer pageNum,
                                     @RequestParam(name = "pageSize",required = true) Integer pageSize) {

        Map returnMap = new HashMap();
        try {

            if (pageNum==null || pageSize==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "无分页信息");
                return  returnMap;
            }

            PageInfo order_lines = weChatService.getYlt_orders_LINE(pageNum,pageSize,b2b_order_number);
            returnMap.put("data",order_lines);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    /**
     * 获取微信小程序 session_key 和 openid
     *
     * @param code 调用微信登陆返回的Code
     * @return
     */
    @RequestMapping("/getSessionKeyOropenid")
    @ResponseBody
    public Object  getSessionKeyOropenid(@RequestParam(name = "code") String code) {
        Map returnMap = new HashMap();
        //微信端登录code值
        String wxCode = code;
        try {
            if (wxCode==null || wxCode.isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "未传入code值");
                return returnMap;
            }
            String requestUrl = SwiftpassConfig.code2Session_url;  //请求地址 https://api.weixin.qq.com/sns/jscode2session
            Map<String, String> requestUrlParam = new HashMap<String, String>();
            requestUrlParam.put("appid", SwiftpassConfig.appID);  //开发者设置中的appId
            requestUrlParam.put("secret", SwiftpassConfig.appSecret); //开发者设置中的appSecret
            requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
            requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code

            //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
            JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
            if (jsonObject.get("openid") !=null) {

                returnMap.put("data",jsonObject);
                returnMap.put("state", "success");
                returnMap.put("msg", "获取成功");
            } else {
                returnMap.put("state", "fail");
                returnMap.put("msg", jsonObject.get("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public  String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            log.debug("line====="+line);
        } catch (Exception e) {
            System.out.println(e);
            log.debug(e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                log.debug(ex);
            }
        }
        return result;
    }

    /**
     * 初始化JSAPI请求，通过生成pay_info来进行交互验证。
     * @return
     */
    @ResponseBody
    @RequestMapping("/initPayInfo")
    public Object initPayInfo(HttpServletResponse resp,HttpServletRequest req
//           ,@RequestParam(name="b2b_order_number" ,required = false)String B2B_ORDER_NUMBER
    ) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            // 前台参数
//            Map userMap = req.getParameterMap();
            //String B2B_ORDER_NUMBER = userMap.get("b2b_order_number")==null?"":userMap.get("b2b_order_number").toString();
            //String openId = userMap.get("openid")==null?"": ((String[]) userMap.get("openid"))[0].toString();
//            String B2B_ORDER_NUMBER = userMap.get("b2b_order_number")==null?"": ((String[]) userMap.get("b2b_order_number"))[0].toString();
//            String SHOP_CUST_ID = userMap.get("shop_cust_id")==null?"":userMap.get("shop_cust_id").toString();
//            String ZDKH_USERID = userMap.get("zdkh_userid")==null?"":userMap.get("zdkh_userid").toString();

            String openId = req.getParameter("openid");
            String B2B_ORDER_NUMBER = req.getParameter("b2b_order_number");
            String SHOP_CUST_ID = req.getParameter("shop_cust_id");
            String ZDKH_USERID = req.getParameter("zdkh_userid");
            // 多个订单合并付款
            String[] B2B_ORDER_NUMBER_ARRAY = B2B_ORDER_NUMBER.split(",");
            if (B2B_ORDER_NUMBER_ARRAY==null || B2B_ORDER_NUMBER_ARRAY.length==0 || openId.isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "传递参数错误");
                return returnMap;
            }
            // 判断订单是否支付
            Map check_b2border_Map = new HashMap();
            check_b2border_Map.put("PAY_STATE", "Y");
            check_b2border_Map.put("B2B_ORDER_NUMBER_ARRAY", B2B_ORDER_NUMBER_ARRAY);
            List check_b2border_List = weChatDao.getPAY_B2B_ORDER_NUMBER(check_b2border_Map);
            if ( check_b2border_List !=null && check_b2border_List.size()>0) {
                Map checkMap = new HashMap();
                for (int i=0;i<check_b2border_List.size();i++) {
                    Map temMap = (Map) check_b2border_List.get(i);
                    checkMap.put(temMap.get("B2B_ORDER_NUMBER"), temMap.get("B2B_ORDER_NUMBER"));
                }
                returnMap.put("state", "fail");
                returnMap.put("msg", "订单已支付,请勿重复支付");
                // 返回支付过的订单号
                // returnMap.put("data",checkMap);
                return returnMap;
            }


            // TODO 具体支付方案未定
            // 获取订单总额(只要金额大于0的)
            check_b2border_Map.put("GT0", "1");
            Map zeMap = weChatDao.getB2B_ORDER_NUMBER_SUM_ORDER_ZE(check_b2border_Map);
            String ORDER_ZE = zeMap.get("SUM_ORDER_ZE")==null?"0":zeMap.get("SUM_ORDER_ZE").toString();
            String SUM_HJ_JE = zeMap.get("SUM_HJ_JE")==null?"0":zeMap.get("SUM_HJ_JE").toString();
            // 检查发运金额和订单金额
            if (Float.parseFloat(ORDER_ZE)<Float.parseFloat(SUM_HJ_JE)) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "支付金额异常,订单金额:"+ORDER_ZE+"实际发货金额:"+SUM_HJ_JE);
                return returnMap;


            } else if ("0".equals(SUM_HJ_JE)) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "实际发货金额为0");
                return returnMap;

            }
            // 把实际发货的金额作为订单支付金额
            ORDER_ZE=SUM_HJ_JE;
            // 商户订单号(支付单号)
            String payId = PkeyGenerator.getUniqueString();
            SortedMap<String,String> map = new TreeMap();
            //XmlUtils.getParameterMap(request);
            // 接口类型
            map.put("service", "pay.weixin.jspay");
            // 版本号，version默认值是2.0
            map.put("version", "2.0");
            // 字符集 可选值 UTF-8 ，默认为 UTF-8
            map.put("charset", "UTF-8");
            // 签名方式:取值RSA_1_256
            map.put("sign_type", "RSA_1_256");
            // 商户号
            map.put("mch_id", SwiftpassConfig.mch_id);
            // 原生JS
            map.put("is_raw", "1");
            // 是否小程序支付
            map.put("is_minipg", "1");
            // 商户订单号(支付单号)
            map.put("out_trade_no", payId);
            // 商品描述
            map.put("body", "药流通订单账款");
            // 用户openid
            map.put("sub_openid", openId);
            // 小程序ID
            map.put("sub_appid", SwiftpassConfig.appID);
            // 附加信息
            map.put("attach", payId);
            // 总金额
            map.put("total_fee", YltUtils.YuanTofen(ORDER_ZE));
            // 终端IP
            map.put("mch_create_ip", YltUtils.getIpAddr(req));
            // 通知地址
            map.put("notify_url", SwiftpassConfig.notify_url);
            // 随机字符串
            map.put("nonce_str", String.valueOf(new Date().getTime()));

            Map<String,String> params = SignUtils.paraFilter(map);
            // System.out.println(params);
            StringBuilder buf = new StringBuilder((params.size() +1) * 10);
            SignUtils.buildPayParams(buf,params,false);
            String preStr = buf.toString();
            String sign_type = map.get("sign_type");
            // 签名
            map.put("sign", SignUtil.getSign(sign_type, preStr));

            // 请求url
            String reqUrl = SwiftpassConfig.req_url;
            //System.out.println("reqUrl：" + reqUrl);

            // System.out.println("reqParams:" + XmlUtils.parseXML(map));
            CloseableHttpResponse response = null;
            CloseableHttpClient client = null;
            String res = null;
            String reSign = null;
            try {
                HttpPost httpPost = new HttpPost(reqUrl);
                StringEntity entityParams = new StringEntity(XmlUtils.parseXML(map),"utf-8");
                httpPost.setEntity(entityParams);
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                if(response != null && response.getEntity() != null){

                    Map<String,String> resultMap = XmlUtils.toMap(EntityUtils.toByteArray(response.getEntity()), "utf-8");

                    reSign = resultMap.get("sign");
                    sign_type = resultMap.get("sign_type");
                    res = XmlUtils.toXml(resultMap);
                    System.out.println("签名方式"+sign_type);
                    if(resultMap.containsKey("sign")){
                        if(SignUtil.verifySign(reSign, sign_type, resultMap)){
                            System.out.println("返回参数验证签名通过。。。");
                            if("0".equals(resultMap.get("status")) && "0".equals(resultMap.get("result_code"))){
//                                DataSourceTransactionManager transactionManager = null;
//                                TransactionStatus status = null;
                                try {
//                                    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
//                                    transactionManager = (DataSourceTransactionManager) wac.getBean("transactionManagement");
//
//                                    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
//                                    definition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE);
//                                    status = transactionManager.getTransaction(definition);// 事务开始
                                    String token_id = resultMap.get("token_id");
                                    Map weChatResultMap = new HashMap();
                                    weChatResultMap.put("token_id", token_id);
                                    weChatResultMap.put("pay_info", resultMap.get("pay_info"));
                                    returnMap.put("state", "success");
                                    returnMap.put("data",weChatResultMap);
                                    returnMap.put("msg",  "生成预支付交易单成功");
                                    // 插入支付信息
                                    Map payMap = new HashMap();
                                    payMap.put("P_ID", payId);
                                    payMap.put("SHOP_CUST_ID", SHOP_CUST_ID);
                                    // 未支付
                                    payMap.put("PAY_STATE", "N");
                                    // 附加信息
                                    payMap.put("ATTACH_INFO", map.get("attach"));
                                    // 订单金额(实际发运的金额)
                                    payMap.put("ORDER_ZE", ORDER_ZE);

                                    payMap.put("ZDKH_USERID", ZDKH_USERID);
                                    weChatDao.insert_YH_ORDER_PAY_HEADER(payMap);
                                    for (String b2bOrder:B2B_ORDER_NUMBER_ARRAY) {
                                        Map lineMap = new HashMap();
                                        lineMap.put("LINE_ID", PkeyGenerator.getUniqueString());
                                        lineMap.put("B2B_ORDER_NUMBER", b2bOrder);
                                        lineMap.put("P_ID", payId);
                                        lineMap.put("PAY_STATE", "N");
                                        weChatDao.insert_YH_ORDER_PAY_LINE(lineMap);
                                        //支付签收订单
                                        Map signMap = new HashMap();
                                        signMap.put("b2b_order_number",b2bOrder);
                                        weChatDao.ylt_signOrder(signMap);
                                    }
                                    Map lineMap = new HashMap();
//                                    transactionManager.commit(status);
                                } catch (Exception e) {
                                    e.printStackTrace();
//                                    transactionManager.rollback(status);
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    returnMap.put("state", "fail");
                                    returnMap.put("msg", "生成预支付交易单失败");

                                    log.error("生成预支付交易单失败:"+B2B_ORDER_NUMBER);
                                }
                            }else{
                                returnMap.put("state", "fail");
                                returnMap.put("msg","生成预支付交易单失败");
                                log.error("生成预支付交易单失败:"+B2B_ORDER_NUMBER);
                            }
                        }
                    }
                }else{
                    res = "操作失败";
                    log.error(res);
                }
            } catch (Exception e) {
                returnMap.put("state", "fail");
                returnMap.put("msg","生成预支付交易单失败");
                log.debug(e);
            } finally {
                if(response != null){
                    response.close();
                }
                if(client != null){
                    client.close();
                }
            }
        } catch (Exception ex) {
            returnMap.put("state", "fail");
            returnMap.put("msg","生成预支付交易单失败");
            System.out.println(ex);
            log.debug(ex);
        }
        return returnMap;
    }

    @RequestMapping("/citicPay/payNotice")
    public void payNotice(HttpServletResponse resp,HttpServletRequest req) {

        String respString = "fail";
        try {
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            String resString = XmlUtils.parseRequst(req);
            // System.out.println("通知内容：" + resString);

            if(resString != null && !"".equals(resString)){
                Map<String,String> map = XmlUtils.toMap(resString.getBytes(), "utf-8");
                Map tempMap = new HashMap();
                tempMap.put("P_ID", map.get("attach"));
                Map stateMap=weChatDao.getYH_ORDER_PAY_HEADER(tempMap);
                if("Y".equals(stateMap.get("PAY_STATE"))) {
                    respString = "success";
                    return;
                }
                String res = XmlUtils.toXml(map);
                String sign_type = map.get("sign_type");
                String reSign = map.get("sign");

                //System.out.println("通知内容：" + res);
                if(map.containsKey("sign")){
                    if(SignUtil.verifySign(reSign, sign_type, map)){
                        String status = map.get("status");
                        if(status != null && "0".equals(status)){
                            String result_code = map.get("result_code");
                            if(result_code != null && "0".equals(result_code)){
                                Map payinMap = new HashMap();
                                payinMap.put("P_ID", map.get("attach"));
                                payinMap.put("PAY_STATE", "Y");
                                payinMap.put("PAY_TIME", map.get("time_end"));
                                payinMap.put("PAY_TYPE", map.get("bank_type"));
                                payinMap.put("RELATE_ORDER_NUMBER", map.get("bank_billno"));
                                payinMap.put("PAY_ZE", YltUtils.fenToYuan(map.get("total_fee")));
                                payinMap.put("TRANSACTION_ID", map.get("transaction_id"));
                                weChatDao.update_PAY_HEADERANDLINE(payinMap);
                            }
                        }
                        respString = "success";
                    }
                }
            }

        } catch (Exception ex) {
            log.debug(ex);
        } finally {
            try {
                resp.getWriter().write(respString);
            } catch (IOException e) {
                e.printStackTrace();
                log.debug(e);
            }
        }
    }

    @ResponseBody
    @RequestMapping( value = "/getYlt_items")
    public Object getYlt_items(@RequestParam Map<String,Object> reqMap) {
        Map returnMap = new HashMap();
        //log.error("*****************************"+reqMap.toString()+reqMap.get("pageNum")+"*****************************");
        try {
            if (reqMap.get("pageNum")==null || reqMap.get("pageSize")==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "无分页信息");
                return  returnMap;
            }
            if(reqMap.get("keyWord")!=null&&!"".equals(reqMap.get("keyWord").toString())){
                reqMap.put("TYM", reqMap.get("keyWord"));
                reqMap.put("T_FACTORY", reqMap.get("keyWord"));
                reqMap.put("ZJM", reqMap.get("keyWord"));
                reqMap.put("TAR_SPBH", reqMap.get("keyWord"));
            }
            PageInfo orders = weChatService.getYlt_items(reqMap);
            returnMap.put("data",orders);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }


    /**
     * 要货登记接口（参数：客户ID，商品ID，店铺ID，数量）
     * @param reqMap
     * @return
     */
    @ResponseBody
    @RequestMapping( value = "/ylt_product_registration")
    public Object ylt_product_registration(@RequestParam Map<String,Object> reqMap) {

        Map returnMap = new HashMap();
        //log.error("*****************************"+reqMap.toString()+reqMap.get("pageNum")+"*****************************");
        try {
            if (reqMap.get("cust_id")==null || reqMap.get("item_code")==null || reqMap.get("shop_cust_id")==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "参数不全");
                log.error("*****************************"+reqMap.toString()+reqMap.get("pageNum")+"*****************************");
                return  returnMap;
            }

            Integer count = weChatDao.check_registration(reqMap);
            if (count>0) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "该商品已报货");
                return  returnMap;
            }

            reqMap.put("reg_id",PkeyGenerator.getUniqueString());
            weChatService.ylt_product_registration(reqMap);
            returnMap.put("data","报货成功");
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }


    @ResponseBody
    @RequestMapping( value = "/get_ylt_product_registration")
    public Object get_ylt_product_registration(@RequestParam Map<String,Object> reqMap) {

        Map returnMap = new HashMap();
        //log.error("*****************************"+reqMap.toString()+reqMap.get("pageNum")+"*****************************");
        try {
            if (reqMap.get("cust_id")==null || reqMap.get("cust_id").toString().isEmpty()) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "终端客户信息未传入");
                return  returnMap;
            }

            PageInfo products = weChatService.get_ylt_product_registration(reqMap);
            returnMap.put("data",products);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    @ResponseBody
    @RequestMapping( value = "/ylt_cancle_registration")
    public Object ylt_cancle_registration(@RequestParam Map<String,Object> reqMap) {

        Map returnMap = new HashMap();
        try {

            weChatService.ylt_cancle_registration(reqMap);
            returnMap.put("data","取消成功");
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }


    /**
     * 签收订单
     * @param reqMap
     * @return
     */
    @ResponseBody
    @RequestMapping( value = "/ylt_signOrder")
    public Object ylt_signOrder(@RequestParam Map<String,Object> reqMap) {

        Map returnMap = new HashMap();
        try {

            weChatService.ylt_signOrder(reqMap);
            returnMap.put("data","签收成功");
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }

    /**
     * 平台用户注册
     * @param reqMap
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/pltsignup")
    public Object pltsignup(@RequestParam Map<String,Object> reqMap) {
        Map returnMap = new HashMap();
        try {
            //｛“MOBILE”:"13312341234"，“NAME”："民康药店”，“YHLX”：“YWY”｝
            List userList=shopChatDao.selectT_USER4Check(reqMap);
            if(userList.size()==0) {
                //insert into t_user
                String ID=PkeyGenerator.getUniqueString();
                reqMap.put("ID", ID);
                shopChatDao.insertT_USER(reqMap);
                returnMap.put("state", "0");
                returnMap.put("msg", "注册成功!");
                returnMap.put("NAME", reqMap.get("NAME"));
                returnMap.put("T_U_ID", ID);
            }else {
                Map userMap=(Map)userList.get(0);
                returnMap.put("state", "1");
                returnMap.put("msg", "手机号已被注册过!");
                returnMap.put("NAME", userMap.get("NAME"));
                returnMap.put("T_U_ID", userMap.get("ID"));
            }
            String token=PkeyGenerator.getUUIDString();
            returnMap.put("token", token);
            String key="token_"+token;
            String T_U_ID=(String)returnMap.get("T_U_ID");
            redisUtil.setEx(key,  T_U_ID, 2, TimeUnit.DAYS);
            returnMap.put("NAME", reqMap.get("NAME"));
            returnMap.put("T_U_ID", T_U_ID);
            returnMap.put("YHLX", reqMap.get("YHLX"));
            key="userinfo_"+T_U_ID;
            redisUtil.hPut(key, "T_U_ID", T_U_ID);
            redisUtil.hPut(key, "MOBILE", reqMap.get("MOBILE").toString());
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "注册失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台可用的配送公司
     * @param
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/availcom")
    public Object availcom(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //｛“MOBILE”：“13312341234”，“PROV”：“河南”，"CITY"：“郑州市”，“COUNY”：“中原区”｝
            JSONObject jsonObject = JSON.parseObject(body);
            reqMap.put("MOBILE", jsonObject.get("MOBILE"));
            reqMap.put("PROV", jsonObject.get("PROV"));
            if(jsonObject.get("CITY")!=null) {
                reqMap.put("CITY", jsonObject.get("CITY"));
            }
            if(jsonObject.get("COUNY")!=null) {
                reqMap.put("COUTY", jsonObject.get("COUNY"));
            }
            List userList=shopChatDao.selectT_USER4Check(reqMap);
            List comList=new ArrayList();
            if(userList.size()==0) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "尚未注册，请先注册用户信息!");
            }else {
                returnMap.put("state", "0");
                comList=weChatDao.availcom(reqMap);
            }
            returnMap.put("availcom", comList);
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台根据配送企业获取可用的业务员信息
     * @param
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/availywy")
    public Object availywy(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //｛“MOBILE”：“13312341234”，“SHOP_CUST_ID”：“150372101132459”｝
            JSONObject jsonObject = JSON.parseObject(body);
            reqMap.put("MOBILE", jsonObject.get("MOBILE"));
            reqMap.put("SHOP_CUST_ID", jsonObject.get("SHOP_CUST_ID"));
            List userList=shopChatDao.selectT_USER4Check(reqMap);
            List retist=new ArrayList();
            if(userList.size()==0) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "尚未注册，请先注册用户信息!");
            }else {
                returnMap.put("state", "0");
                retist=weChatDao.availywy(reqMap);
            }
            returnMap.put("availywy", retist);
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台用户注册到配送企业
     * @param
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/signup")
    public Object signup(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //｛“MOBILE”：“13312341234”，“SHOP_CUST_ID”：“150372101132459”，
            //“CUST_ID”：“1504690576742135”，“U_ACCOUNT”：“13312341234”，“CUST_NAME”：“民康药店”，
            //“SHDZ”：“收货地址”，“SHLXR”：“收货人(默认是姓名)”，“YWY_ID”：“12313”,"YHLX"：“YD”,"YWY_NAME":""｝
            JSONObject jsonObject = JSON.parseObject(body);
            
            reqMap.put("SHOP_CUST_ID", jsonObject.get("SHOP_CUST_ID"));//店铺ID//2、配送公司
            reqMap.put("YWY_NAME", jsonObject.get("YWY_NAME"));//3、业务员姓名
            reqMap.put("YWY_ID", jsonObject.get("YWY_ID"));//3、业务员
            reqMap.put("YHLX", jsonObject.get("YHLX"));//4、收货单位类型
            reqMap.put("CUST_ID", jsonObject.get("CUST_ID"));//5、单位ID
            reqMap.put("CUST_NAME", jsonObject.get("CUST_NAME"));//5、收货单位名称
            reqMap.put("SHLXR", jsonObject.get("SHLXR"));//6、收货联系人
            reqMap.put("MOBILE", jsonObject.get("MOBILE"));//手机号//7、登录账号
            reqMap.put("U_ACCOUNT", jsonObject.get("U_ACCOUNT"));//7、收货手机
            reqMap.put("SHDZ", jsonObject.get("SHDZ"));//8、收货地址
            List userList=shopChatDao.selectT_USER4Check(reqMap);
			
            List retist=new ArrayList();
            if(userList.size()==0) {//APP端是否注册过
                returnMap.put("state", "-1");
                returnMap.put("msg", "尚未注册，请先注册用户信息!");
            }else {//APP端注册过
                returnMap.put("state", "0");
                Map userMap=(Map)userList.get(0);
                String token=PkeyGenerator.getUUIDString();
                String key="token_"+token;
                String T_U_ID=userMap.get("ID").toString();
                redisUtil.setEx(key,  T_U_ID, 2, TimeUnit.DAYS);
                returnMap.put("NAME", userMap.get("NAME"));
                returnMap.put("T_U_ID", T_U_ID);
                key="userinfo_"+T_U_ID;
                redisUtil.hPut(key, "T_U_ID", T_U_ID);
                redisUtil.hPut(key, "MOBILE", reqMap.get("MOBILE").toString());
                reqMap.put("T_U_ID", userMap.get("ID"));
                List pcUserList=weChatDao.selectPcUser(reqMap);//pc端是否注册过
                if(pcUserList.size()==0) {//pc端没有注册过
                    if(reqMap.get("U_PASSWORD")==null) {
                        reqMap.put("U_PASSWORD", "96e79218965eb72c92a549dd5a330112");
                    }else {
                        reqMap.put("U_PASSWORD",MD5UtilSecurity.md5Digest(reqMap.get("U_PASSWORD").toString()));
                    }
                    if("YWY".equals(reqMap.get("YHLX"))) {//用户类型是业务员
                        //公司业务员或者自然人业务员注册ZZQX_USERS,ZZQX_USER_ROLES
                        reqMap.put("U_ID", PkeyGenerator.getUniqueString());
                        reqMap.put("CUST_ID", reqMap.get("SHOP_CUST_ID"));
                        weChatDao.insert_ZZQX_USERS(reqMap);
                        reqMap.put("R_ID", "202002001");
                        weChatDao.insert_ZZQX_USER_ROLES(reqMap);
                        reqMap.put("R_ID", PkeyGenerator.getUniqueString());
                        shopChatDao.insertYLT_USER_SHOP_REL(reqMap);
                    }else{
                        log.error("$$$$$$$$"+reqMap);
                        String CUST_ID=(String)reqMap.get("CUST_ID");
                        if(reqMap.get("CUST_ID")==null||"".equals(CUST_ID)) {//未对接系统的情况
                            List custList=weChatDao.selectCust4Check(reqMap);
                            if(custList.size()==0) {
                                //注册到ylt_CUSTOMERS,YLT_CUSTOMER_SHOP_REL,
                                CUST_ID=PkeyGenerator.getUniqueString();
                                reqMap.put("CUST_ID", CUST_ID);
                                weChatDao.insertYLT_CUSTOMER(reqMap);
                                weChatDao.insertYLT_CUSTOMER_SHOP_REL(reqMap);
                            }else{//客户已注册只是要注册账号以及业务员关系
                                Map custMap=(Map)custList.get(0);
                                CUST_ID=(String)custMap.get("CUST_ID");
                            }
                            reqMap.put("CUST_ID", CUST_ID);
                        }
                        //注册到YLT_YWY_CUST_REL,YLT_CUST_CONTACT,ZZQX_USERS,ZZQX_USER_ROLES,
                        List ywyCustList=weChatDao.ywyCustList(reqMap);
                        if(ywyCustList.size()==0) {
                            //插入关系表
                            reqMap.put("GX_ID", PkeyGenerator.getUniqueString());
                            weChatDao.insertYLT_YWY_CUST_RLT(reqMap);
                        }
                        List priceList=weChatDao.selectPriceList(reqMap);
                        if(priceList.size()>0) {
                            Map pMap=(Map)priceList.get(0);
                            reqMap.put("PRICE_LIST", pMap.get("JMB_ID"));
                        }

                        String U_ID=PkeyGenerator.getUniqueString();
                        reqMap.put("U_ID", U_ID);
                        reqMap.put("YHLX", "ZDKH");
                        weChatDao.insert_ZZQX_USERS(reqMap);
                        //默认为选中标志
                        reqMap.put("U_ID", U_ID);
                        reqMap.put("T_U_ID", T_U_ID);
                        shopChatDao.updateT_USERS_LASTSHOPID(reqMap);
                        reqMap.put("R_ID", "11088");
                        weChatDao.insert_ZZQX_USER_ROLES(reqMap);
                        reqMap.put("CONTACT_ID", PkeyGenerator.getUniqueString());
                        weChatDao.insertYLT_CUST_CONTACT(reqMap);
                        //插入电脑与手机账号关系
                        reqMap.put("R_ID", PkeyGenerator.getUniqueString());
                        shopChatDao.insertYLT_USER_SHOP_REL(reqMap);
                        
                        List contactList=weChatDao.selectYLT_CUST_CONTACT(reqMap);
                        returnMap.put("CONTACT_LIST", contactList);
                        returnMap.put("token", token);
                    }
                }else {
                    //账号已注册过
                    if("YWY".equals(reqMap.get("YHLX"))) {
                        //公司业务员或者自然人业务员注册ZZQX_USERS,ZZQX_USER_ROLES
                    	returnMap.put("state", "-1");
                        returnMap.put("msg", "获取信息失败，请联系平台客服!");
                    }else{
                        log.error("$$$$$$$$"+reqMap);
                        String CUST_ID=(String)reqMap.get("CUST_ID");
                        if(reqMap.get("CUST_ID")==null||"".equals(CUST_ID)) {//未对接系统的情况
                            List custList=weChatDao.selectCust4Check(reqMap);
                            if(custList.size()==0) {
                                //注册到ylt_CUSTOMERS,YLT_CUSTOMER_SHOP_REL,
                                CUST_ID=PkeyGenerator.getUniqueString();
                                reqMap.put("CUST_ID", CUST_ID);
                                weChatDao.insertYLT_CUSTOMER(reqMap);
                                weChatDao.insertYLT_CUSTOMER_SHOP_REL(reqMap);
                            }else{//客户已注册只是要注册账号以及业务员关系
                                Map custMap=(Map)custList.get(0);
                                CUST_ID=(String)custMap.get("CUST_ID");
                            }
                            reqMap.put("CUST_ID", CUST_ID);
                        }
                        //注册到YLT_YWY_CUST_REL,YLT_CUST_CONTACT,ZZQX_USERS,ZZQX_USER_ROLES,
                        List ywyCustList=weChatDao.ywyCustList(reqMap);
                        if(ywyCustList.size()==0) {
                            //插入关系表
                            reqMap.put("GX_ID", PkeyGenerator.getUniqueString());
                            weChatDao.insertYLT_YWY_CUST_RLT(reqMap);
                        }
                        List priceList=weChatDao.selectPriceList(reqMap);
                        if(priceList.size()>0) {
                            Map pMap=(Map)priceList.get(0);
                            reqMap.put("PRICE_LIST", pMap.get("JMB_ID"));
                        }
                        
                        Map pcMap=(Map)pcUserList.get(0);
                        String U_ID=pcMap.get("U_ID").toString();
                        //默认为选中标志
                        reqMap.put("U_ID", U_ID);
                        reqMap.put("T_U_ID", T_U_ID);
                        shopChatDao.updateT_USERS_LASTSHOPID(reqMap);
                        reqMap.put("CONTACT_ID", PkeyGenerator.getUniqueString());
                        weChatDao.insertYLT_CUST_CONTACT(reqMap);
                        //插入电脑与手机账号关系
                        reqMap.put("R_ID", PkeyGenerator.getUniqueString());
                        shopChatDao.insertYLT_USER_SHOP_REL(reqMap);
                        
                        List contactList=weChatDao.selectYLT_CUST_CONTACT(reqMap);
                        returnMap.put("CONTACT_LIST", contactList);
                        returnMap.put("token", token);
                    }
                }
            }
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台用户登录
     * @param reqMap
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/login")
    public Object login(@RequestParam Map<String,Object> reqMap) {
        Map returnMap = new HashMap();
        try {
            //{"MOBILE":"13312341234"}
        	log.debug("==============================================="+reqMap);
        	String code=(String)reqMap.get("code");
        	if(code!=null) {
        		XcxPay xp=new XcxPay();
        		Map m=xp.getSessionKeyOropenid(code);
        		returnMap.put("openId", m.get("openId"));
        	}
        	
            List userList=shopChatDao.selectT_USER4Check(reqMap);
            List retist=new ArrayList();
            if(userList.size()==0) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "尚未注册，请先注册用户信息!");
            }else {
                returnMap.put("state", "0");
                Map userMap=(Map)userList.get(0);
                reqMap.put("T_U_ID", userMap.get("ID"));
                List t_userList=shopChatDao.selectYLT_USER_SHOP_REL(reqMap);
                List ACCOUNT_LIST=new ArrayList();
                for(int i=0;i<t_userList.size();i++) {
                    Map zuMap=(Map)t_userList.get(i);
                    if(zuMap.get("LASTUSERID")==null) {
                    	zuMap.put("LASTUSERID", "-1");
                    }
                    List thisList=weChatDao.selectZZQX_USERS(zuMap);
                    ACCOUNT_LIST.addAll(thisList);
                }
                String token=PkeyGenerator.getUUIDString();
                String key="token_"+token;
                String T_U_ID=userMap.get("ID").toString();
                redisUtil.setEx(key,  T_U_ID, 2, TimeUnit.DAYS);
                key="userinfo_"+T_U_ID;
                redisUtil.hPut(key, "T_U_ID", T_U_ID);
                redisUtil.hPut(key, "MOBILE", reqMap.get("MOBILE").toString());
                returnMap.put("ACCOUNT_LIST", ACCOUNT_LIST);
                returnMap.put("T_U_ID", userMap.get("ID"));
                returnMap.put("NAME", userMap.get("NAME"));
                returnMap.put("YHLX", userMap.get("YHLX"));
                returnMap.put("token", token);
            }
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台用户登录
     * @param
     * @return
     */
    @ResponseBody
    @PostMapping( value = "/login4com")
    public Object login4com(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //｛“token”："Q***********E*******"，“SHOP_CUST_ID”:"150372101132459"，“U_ID”：“1233121”｝
            JSONObject jsonObject = JSON.parseObject(body);
            Object token=jsonObject.get("token");
            if(token==null) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "缺少参数token!");
            }else {
                String key="token_"+token;
                String T_U_ID=redisUtil.get(key);
                if(T_U_ID==null) {
                    returnMap.put("state", "-1");
                    returnMap.put("msg", "token失效,请重新登录!");
                }else {
                    returnMap.put("state", "0");
                    reqMap.put("SHOP_CUST_ID", jsonObject.get("SHOP_CUST_ID"));
                    reqMap.put("U_ID", jsonObject.get("U_ID"));
                    List contactList=weChatDao.selectYLT_CUST_CONTACT(reqMap);
                    returnMap.put("CONTACT_LIST", contactList);
                    returnMap.put("token", token);
                    reqMap.put("T_U_ID", T_U_ID);
                    shopChatDao.updateT_USERS_LASTSHOPID(reqMap);
                }
            }
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    /**
     *  平台用户配送公司列表、账号、收货地址
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping( value = "/availInfo",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object availInfo(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //{"token":"231sdsadsad233221qwww"}
            JSONObject jsonObject = JSON.parseObject(body);
            Object token=jsonObject.get("token");
            if(token==null) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "缺少参数token!");
            }else {
                String key="token_"+token;
                String T_U_ID=redisUtil.get(key);
                if(T_U_ID==null) {
                    returnMap.put("state", "-1");
                    returnMap.put("msg", "token失效,请重新登录!");
                }else {
                    returnMap.put("state", "0");
                    reqMap.put("T_U_ID", T_U_ID);
                    List t_userList=shopChatDao.selectYLT_USER_SHOP_REL(reqMap);
                    List ACCOUNT_LIST=new ArrayList();
                    for(int i=0;i<t_userList.size();i++) {
                        Map zuMap=(Map)t_userList.get(i);
                        if(zuMap.get("LASTUSERID")==null) {
                        	zuMap.put("LASTUSERID", "-1");
                        }
                        List thisList=weChatDao.selectZZQX_USERS(zuMap);
                        ACCOUNT_LIST.addAll(thisList);
                    }
                    returnMap.put("ACCOUNT_LIST", ACCOUNT_LIST);
                    returnMap.put("T_U_ID", T_U_ID);
                    returnMap.put("token", token);
                }
            }
        } catch (Exception e) {
            returnMap.put("state", "-1");
            returnMap.put("msg", "获取信息失败，请联系平台客服!");
            log.error("pltsignup"+reqMap, e);
        }
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getYlt_orders_header_fk",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object getYlt_orders_header_fk(@RequestBody String body) {

        Map returnMap = new HashMap();
        Map reqMap = new HashMap();
        try {
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject.get("CUST_ID")==null ) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "客户未传入");
                return  returnMap;
            }
            if (jsonObject.get("pageNum")==null || jsonObject.get("pageSize")==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "无分页信息");
                return  returnMap;
            }
            if (jsonObject.get("SHOP_CUST_ID")==null ) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "商家未传入");
                return  returnMap;
            }
            String order_zt=jsonObject.get("ORDER_TYPE").toString();
            if ("1".equals(order_zt)){
                reqMap.put("CXTJARR","23,5,6,7".split(","));
                reqMap.put("PAY_STATE",null);
            }else if ("2".equals(order_zt)){
                reqMap.put("CXTJARR","23,5".split(","));
                reqMap.put("PAY_STATE",'N');
            }else if ("3".equals(order_zt)){
                reqMap.put("CXTJARR","6".split(","));
                reqMap.put("PAY_STATE",'N');
            }else if ("4".equals(order_zt)){
                reqMap.put("CXTJARR","6,7".split(","));
                reqMap.put("PAY_STATE",'N');
            }else {
                reqMap.put("CXTJARR","7".split(","));
                reqMap.put("PAY_STATE", 'Y');
            }

            reqMap.put("SHOP_CUST_ID", jsonObject.get("SHOP_CUST_ID"));
            reqMap.put("CUST_ID", jsonObject.get("CUST_ID"));
            reqMap.put("pageNum", jsonObject.get("pageNum"));
            reqMap.put("pageSize", jsonObject.get("pageSize"));

            PageInfo ordersList =null;
            //如果是全部订单和待发订单，是从订单表里取的数据，否则是从发运表里取的数据
            if ("1".equals(order_zt)||"2".equals(order_zt)) {
                ordersList = weChatService.getYlt_orders_header_fk(reqMap);
            }else {
                ordersList = weChatService.getYlt_delivers_header_fk(reqMap);
            }
            returnMap.put("data",ordersList);
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getYlt_Order_Item",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object getYlt_Order_Item(HttpServletRequest request, @RequestBody String body) {
        Map reqMap= new HashMap();
        Map returnMap = new HashMap();
        try {
        	//{"token":"e3c103f169a34947b66e1a4658396547","pageNum":"1","pageSize":"20","B2B_ORDER_NUMBER":"835073","DATA_TYPE":"dlv"}
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject.get("B2B_ORDER_NUMBER")==null || jsonObject.get("B2B_ORDER_NUMBER")==null) {
                returnMap.put("state", "fail");
                returnMap.put("msg", "参数错误");
                return  returnMap;
            }
            if(jsonObject.get("pageNum")==null||"".equals(jsonObject.get("pageNum"))) {
            	jsonObject.put("pageNum",1);
            	jsonObject.put("pageSize",1000);
            }
            if(jsonObject.get("DATA_TYPE")==null||"".equals(jsonObject.get("DATA_TYPE"))) {
            	jsonObject.put("DATA_TYPE","dlv");
            }
            String data_type=jsonObject.get("DATA_TYPE").toString();
            reqMap.put("B2B_ORDER_NUMBER", jsonObject.get("B2B_ORDER_NUMBER"));
            reqMap.put("pageNum", jsonObject.get("pageNum"));
            reqMap.put("pageSize", jsonObject.get("pageSize"));
            PageInfo order_lines =null;
            if("order".equals(data_type)){
                order_lines = weChatService.getYlt_Order_Item(reqMap);
            }else{
                order_lines = weChatService.getYlt_Deliver_Item(reqMap);
                Kv pr = wxHandle.doRecodPay(jsonObject,order_lines,shopChatDao,YltUtils.getIpAddr(request));
                if(pr!=null&&pr.getBoolean("status")) {
                	returnMap.put("state", 1);
	                pr.put("details", order_lines);
	        		returnMap.put("data",pr);
	        		returnMap.put("msg", "操作成功");
                }else {
                	log.error("reqMap========="+reqMap);
                	returnMap.put("state", 0);
                	returnMap.put("msg", "操作失败，请稍后再试!");                	
                }
            }
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败，请稍后再试");
            log.debug(e);
        }

        return returnMap;
    }
    @ResponseBody
    @RequestMapping( value = "/ylt_editOrderZt",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object ylt_editOrderZt(@RequestBody String body) {
        Map reqMap= new HashMap();
        Map returnMap = new HashMap();
        try {
            JSONObject jsonObject = JSON.parseObject(body);

            reqMap.put("B2B_ORDER_NUMBER", jsonObject.get("B2B_ORDER_NUMBER"));
            reqMap.put("SO_ZT", jsonObject.get("SO_ZT"));

            weChatService.update_Order_Header_ZT(reqMap);
            returnMap.put("data","修改成功");
            returnMap.put("state", "success");
            returnMap.put("msg", "操作成功");
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            e.printStackTrace();
            log.debug(e);
        }

        return returnMap;
    }



    @ResponseBody
    @RequestMapping( value = "/ItemPrice")
    public Object select_ItemPrice(@RequestBody String body) {
        Map returnMap = new HashMap();
        Map reqMap=new HashMap();
        try {
            //{"token":"e3c103f169a34947b66e1a4658396547","keyWord":"萘敏","pageNum":"1","pageSize":"20","SHOP_CUST_ID":"15439949454639","CUST_ID":"16139843929245"}
            JSONObject jsonObject = JSON.parseObject(body);
            Object token=jsonObject.get("token");
            if(token==null) {
                returnMap.put("state", "-1");
                returnMap.put("msg", "缺少参数token!");
            }else {
                String key="token_"+token;
                if (jsonObject.get("pageNum")==null || jsonObject.get("pageSize")==null) {
                    returnMap.put("state", "fail");
                    returnMap.put("msg", "无分页信息");
                    return  returnMap;
                }
                reqMap.put("pageNum", jsonObject.get("pageNum"));
                reqMap.put("pageSize", jsonObject.get("pageSize"));
                if(jsonObject.get("SHOP_CUST_ID")==null || jsonObject.get("CUST_ID")==null) {
                    returnMap.put("state", "fail");
                    returnMap.put("msg", "参数信息错误");
                    return  returnMap;
                }
                reqMap.put("SHOP_CUST_ID", jsonObject.get("SHOP_CUST_ID"));
                reqMap.put("CUST_ID", jsonObject.get("CUST_ID"));
                if(jsonObject.get("keyWord")!=null&&!"".equals(jsonObject.get("keyWord").toString())){
                    reqMap.put("TYM", jsonObject.get("keyWord"));
                    reqMap.put("keyWord", jsonObject.get("keyWord"));
                    reqMap.put("T_FACTORY", jsonObject.get("keyWord"));
                    reqMap.put("ZJM", jsonObject.get("keyWord"));
                    reqMap.put("TAR_SPBH", jsonObject.get("keyWord"));
                }
                PageInfo item = weChatService.select_ItemPrice(reqMap);
                returnMap.put("data",item);
                returnMap.put("state", "success");
                returnMap.put("msg", "操作成功");
                returnMap.put("token", token);
            }
        } catch (Exception e) {
            returnMap.put("state", "fail");
            returnMap.put("msg", "操作失败");
            log.debug(e);
        }

        return returnMap;
    }

    @RequestMapping("/validate")
    public void validate(HttpServletRequest request, HttpServletResponse response) {
    	try {
    		WeixinServlet ws=new WeixinServlet();
    		ws.doGet(request, response);
    	}catch(Exception ex) {
    		log.error(ex.getMessage(),ex);
    	}
    }
    
    /**
     * 支付结果异步通知处理<br/>
     * 说明：关于attach参数，该参数是支付预下单时提交给支付渠道的参数，在支付成功后异步通知时还能原样带回来，目的是希望在支付前将一些参数参带给支付后的处理逻辑，目前移动端
     * 支付渠道都有该参数，但是PC端收银台支付渠道对接时发现，该方式没有attach参数，所以搞了一个特例，在PC端支付时，通过在notifyUrl地址后显示拼接参数，以达到透传参数的目的
     * @param request HttpServletRequest实例
     * @param SHOP_CUST_ID PC支付时传入的店铺ID，PC端调起收银台支付接口时会传入
     * @param PAY_TRANSNO PC支付时传入的订单编号，PC端调起收银台支付接口时会传入
     * @param U_ID PC支付时传入的用户ID，PC端调起收银台支付接口时会传入
     */
    @ResponseBody
    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request,String SHOP_CUST_ID,String PAY_TRANSNO,String U_ID) {

        try {
            //支付返回的是json串，再转换为string，
            request.setCharacterEncoding("utf-8");
            
            BufferedReader br = request.getReader();
            String line="";
            StringBuffer sb=new StringBuffer();
            while((line = br.readLine()) != null){
            	sb.append(line);
            }
            String content = new String(sb.toString().getBytes("ISO8859-1"),"UTF-8");
            log.debug("收到支付异步通知，内容：" + content);
            if(StringUtils.isEmpty(content)||!JSONUtil.isJson(content)) {
            	return "fail";
            }
            JSONObject jsonObject = JSON.parseObject(content);
            String retCode=jsonObject.getString("retcode");//"0200"
            String trade_state=jsonObject.getString("tradeState");//交易状态:支付结果：0—成功1—失败3-处理中4支付成功等待确认收货 6-订单关闭
            if("0".equals(trade_state)&&"0".equals(retCode)){
            	String outTradeNo=jsonObject.getString("outTradeNo");//我方订单号
            	String   subpartner=jsonObject.getString("subpartner");
                //attach:里面存储shop_cust_id，b2b_order_number,pay_u_id,，约定把订单号存到attach中
                String   partner=jsonObject.getString("partner");
                //根据支付流水号调用查询接口查询银行支付单
                Kv params = Kv.create()
                        .set("subpartner", subpartner)//特约商户号
                        .set("outTradeNo",outTradeNo);//商户订单号
                Kv result=com.utils.tfzf.Api.queryOrder(params);
                if(result.getBoolean("status")){
                    String pay_TransNo=result.getStr("payTransno");//在渠道中的商品订单号,这个值好像没有用
                    String trans_channel=result.getStr("transChannel");//支付渠道
                    String timeEnd=result.getStr("timeEnd");//支付完成时间yyyyMMdd HH：mm：ss
                    String bank_type=result.getStr("bankType");//银行类型，默认为“DEFAULT”－天府支付。,返回的是null
                    String returnSerNo=result.getStr("returnSerNo");
                    String totalFee = result.getStr("totalFee");//
                    String feeType=result.getStr("feeType");
                    String bankTransNo=result.getStr("bankTransNo");
                    String transactionId=result.getStr("transactionId");//天府银行订单流水号
                    String payTransNo=result.getStr("payTransNo");//这个是支付订单后，流转的，不用记录

                    String attach=result.getStr("attach");//商家数据包,原样返回；约定包含：店铺号、订单号、支付人U，以“|”分割。
                    String shop_cust_id = null, b2b_order_number = null, pay_u_id = null;
                    if(!StringUtils.isEmpty(attach)) {
                    	//当attach参数不为空时，解析
                    	String[] splitatt=attach.split("\\|");
                    	shop_cust_id=splitatt[0]==null?"":splitatt[0].toString();//店铺shop_cust_id
                    	b2b_order_number=splitatt[1]==null?"":splitatt[1].toString();//订单号
                    	pay_u_id=splitatt[2]==null?"":splitatt[2].toString();//付款人u_id
                    }else if(!StringUtils.isEmpty(SHOP_CUST_ID)&&!StringUtils.isEmpty(PAY_TRANSNO)&&!StringUtils.isEmpty(U_ID)){
                    	//当请求参数中显示携带attach参数时，解析
                    	shop_cust_id = SHOP_CUST_ID;
                    	b2b_order_number = PAY_TRANSNO;
                    	pay_u_id = U_ID;
                    }else{
                    	//没有attach参数时，直接返回失败
                    	return "fail";
                    }

                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
                    Date sysDate = new Date();
                    String nowDate=df.format(sysDate);
                    Map paymap = new HashMap();
                    paymap.put("NOT_ID", PkeyGenerator.getUniqueString());
                    paymap.put("PAY_U_ID", pay_u_id);
                    paymap.put("TRANSACTION_ID", transactionId);//支付流水号
                    paymap.put("PAY_TYPE", trans_channel);//支付渠道
                    paymap.put("PARTNER", partner);
                    paymap.put("PAY_TRANSNO", payTransNo);//商品在渠道中的订单号支付时产生
                    paymap.put("OUT_TRANSNO", outTradeNo);// ylt平台生成的商品订单号
                    paymap.put("SUBPARTNER", subpartner);//特约商户号
                    paymap.put("TOTAL_FEE", totalFee);//支付总费用
                    paymap.put("FEE_TYPE", feeType);//支付币种
                    paymap.put("TIME_END", timeEnd);//支付完成时间
                    paymap.put("TRADE_STATE", trade_state);
                    paymap.put("ATTACH", attach);
                    paymap.put("RETURNSERNO", returnSerNo);
                    paymap.put("RETCODE", retCode);
                    paymap.put("BANK_TYPE", bank_type);
                    paymap.put("BANK_TRANSNO", bankTransNo);
                    paymap.put("CJSJ", nowDate);
                    paymap.put("SHOP_CUST_ID", shop_cust_id);
                    paymap.put("B2B_ORDER_NUMBER", b2b_order_number);

                    Timestamp   payTime= Timestamp.valueOf(timeEnd);

                    List tempNotist = shopChatDao.selectPayIfExist(paymap);
                    if(tempNotist==null|| tempNotist.size()==0){//不存在的时候插入通知，并进行业务处理，否则是已经处理过，跳出
                        int reNoticet = shopChatDao.insertPayNotice(paymap);//插入支付通知
                        if(reNoticet!=0){//回填支付头、支付行、订单行的支付状态
                            Map payHmap = new HashMap();
                            payHmap.put("PAY_ZT", "Y");
                            payHmap.put("PAY_U_ID", pay_u_id);
                            payHmap.put("TRANSACTION_ID", transactionId);
                            payHmap.put("PAY_END_TIME", payTime);
                            payHmap.put("PAY_TYPE", trans_channel);
                            payHmap.put("OUT_TRANSNO", outTradeNo);// ylt平台生成的商品订单号
                            payHmap.put("PAY_TRANSNO", payTransNo);//在支付渠道中生产的商品订单号
                            shopChatDao.updatePayHeaderZT(payHmap);//

                            //修改订单头的支付状态和支付时间
                            Map orderHmap = new HashMap();
                            String B2B_ORDER_NUMBER=b2b_order_number;
                            orderHmap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
                            orderHmap.put("PAY_STATE", "Y");//支付状态该为已支付
                            orderHmap.put("SO_ZT", "7");//订单状态改为7
                            orderHmap.put("PAY_TIME", payTime);
                            orderHmap.put("ORDER_GXSJ", sysDate);
                            orderHmap.put("PAY_U_ID", pay_u_id);
                            orderHmap.put("PAY_TYPE",trans_channel);
                            weChatDao.updateOrderHPayZT(orderHmap);//回填更新订单头的支付状态

                            List payHList = shopChatDao.selectPayHByTransno(payHmap);
                            if (payHList != null && payHList.size() > 0) {
                                payHmap = (Map) payHList.get(0);
                                List payLList = shopChatDao.selectPayLByHID(payHmap);
                                if (payLList != null && payLList.size() > 0) {
                                    for (int i = 0; i < payLList.size(); i++) {
                                        Map payLmap=(Map) payLList.get(i);
                                        payLmap.put("TRANSACTION_ID", transactionId);
                                        payLmap.put("PAY_TRANSNO", payTransNo);
                                        payLmap.put("OUT_TRANSNO", outTradeNo);
                                        payLmap.put("PAY_END_TIME", payTime);
                                        payLmap.put("PAY_ZT", "Y");
                                        payLmap.put("PAY_U_ID", pay_u_id);
                                        shopChatDao.updatePayLineZT(payLmap);//更新支付行支付数据

                                        //更新发运行状态,
                                        Map orderLMap = new HashMap();
                                        orderLMap.put("DLV_LINE_ID", payLmap.get("DLV_LINE_ID"));
                                        orderLMap.put("PAY_TIME", payTime);
                                        orderLMap.put("PAY_STATE", "Y");
                                        weChatDao.updateDlvLinePayZT(orderLMap);//回填更新发运行的支付状态

                                   }
                                }
                            }

                        }
                    }
                }
            }
            return  "success";
    	}catch(Exception ex) {
    		log.error(ex.getMessage(),ex);
            return "fail";
    	}

    }
    /*返回接收URL*/
    @ResponseBody
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request) {
        try {
            System.out.println("同步通知");
            request.setCharacterEncoding("utf-8");

            JSONObject jsonObject = JSON.parseObject(request.getParameterMap().toString());
            String retCode = jsonObject.getString("code");//"0200"
            String retMsg = jsonObject.getString("message");//"success"
            String trade_state = jsonObject.getString("status");//交易状态:支付结果：0—成功1—失败3-处理中4支付成功等待确认收货 6-订单关闭
            if ("1".equals(trade_state)) {
                return "success";
            } else {
                return "fail";
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return "success";
    }
    
    /*公众号JSAPI*/
    @RequestMapping("/jssdk")
    public void jssdk(HttpServletRequest request, HttpServletResponse response) {
    	try {
    		String url=request.getParameter("url");
    		Map<String, String> configMap = JSSDK_Config.jsSDK_Sign(url,redisUtil);
    		String json=JSONObject.toJSONString(configMap);
    		response.setContentType("application/json;charset=utf-8");
    		log.debug("json========"+json);
    		response.getWriter().write(json);
    	}catch(Exception ex) {
    		log.error(ex.getMessage(),ex);
    	}
    }


    @ResponseBody
    @RequestMapping(value ="/notifyUrl2",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public String notifyUrl2(@RequestBody String body) {

        try {
            //支付返回的是json串，再转换为string，
//            request.setCharacterEncoding("utf-8");
//
//            BufferedReader br = request.getReader();
//            String line="";
//            StringBuffer sb=new StringBuffer();
//            while((line = br.readLine()) != null){
//                sb.append(line);
//            }
//            String content = new String(sb.toString().getBytes("ISO8859-1"),"UTF-8");
//            log.debug("收到支付异步通知，内容：" + content);
//            if(StringUtils.isEmpty(content)||!JSONUtil.isJson(content)) {
//                return "fail";
//            }
            JSONObject jsonObject = JSON.parseObject(body);
            String retCode=jsonObject.getString("retcode");//"0200"
            String trade_state=jsonObject.getString("tradeState");//交易状态:支付结果：0—成功1—失败3-处理中4支付成功等待确认收货 6-订单关闭
            if("0".equals(trade_state)&&"0".equals(retCode)){
                String outTradeNo=jsonObject.getString("outTradeNo");//我方订单号
                String   subpartner=jsonObject.getString("subpartner");
                //attach:里面存储shop_cust_id，b2b_order_number,pay_u_id,，约定把订单号存到attach中
                String   partner=jsonObject.getString("partner");
                //根据支付流水号调用查询接口查询银行支付单
                Kv params = Kv.create()
                        .set("subpartner", subpartner)//特约商户号
                        .set("outTradeNo",outTradeNo);//商户订单号
                Kv result=com.utils.tfzf.Api.queryOrder(params);
                if(result.getBoolean("status")){
                    String pay_TransNo=result.getStr("payTransno");//在渠道中的商品订单号,这个值好像没有用
                    String trans_channel=result.getStr("transChannel");//支付渠道
                    String timeEnd=result.getStr("timeEnd");//支付完成时间yyyyMMdd HH：mm：ss
                    String bank_type=result.getStr("bankType");//银行类型，默认为“DEFAULT”－天府支付。,返回的是null
                    String returnSerNo=result.getStr("returnSerNo");
                    String totalFee = result.getStr("totalFee");//
                    String feeType=result.getStr("feeType");
                    String bankTransNo=result.getStr("bankTransNo");
                    String transactionId=result.getStr("transactionId");//天府银行订单流水号
                    String payTransNo=result.getStr("payTransNo");//这个是支付订单后，流转的，不用记录

                    String attach=result.getStr("attach");//商家数据包,原样返回；约定包含：店铺号、订单号、支付人U，以“|”分割。
                    String[] splitatt=attach.split("\\|");
                    String   shop_cust_id=splitatt[0]==null?"":splitatt[0].toString();//店铺shop_cust_id
                    String   b2b_order_number=splitatt[1]==null?"":splitatt[1].toString();//订单号
                    String   pay_u_id=splitatt[2]==null?"":splitatt[2].toString();//付款人u_id


                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
                    Date sysDate = new Date();
                    String nowDate=df.format(sysDate);
                    Map paymap = new HashMap();
                    paymap.put("NOT_ID", PkeyGenerator.getUniqueString());
                    paymap.put("PAY_U_ID", pay_u_id);
                    paymap.put("TRANSACTION_ID", transactionId);//支付流水号
                    paymap.put("PAY_TYPE", trans_channel);//支付渠道
                    paymap.put("PARTNER", partner);
                    paymap.put("PAY_TRANSNO", payTransNo);//商品在渠道中的订单号支付时产生
                    paymap.put("OUT_TRANSNO", outTradeNo);// ylt平台生成的商品订单号
                    paymap.put("SUBPARTNER", subpartner);//特约商户号
                    paymap.put("TOTAL_FEE", totalFee);//支付总费用
                    paymap.put("FEE_TYPE", feeType);//支付币种
                    paymap.put("TIME_END", timeEnd);//支付完成时间
                    paymap.put("TRADE_STATE", trade_state);
                    paymap.put("ATTACH", attach);
                    paymap.put("RETURNSERNO", returnSerNo);
                    paymap.put("RETCODE", retCode);
                    paymap.put("BANK_TYPE", bank_type);
                    paymap.put("BANK_TRANSNO", bankTransNo);
                    paymap.put("CJSJ", nowDate);
                    paymap.put("SHOP_CUST_ID", shop_cust_id);
                    paymap.put("B2B_ORDER_NUMBER", b2b_order_number);

                    Timestamp   payTime= Timestamp.valueOf(timeEnd);

                    List tempNotist = shopChatDao.selectPayIfExist(paymap);
                    if(tempNotist==null|| tempNotist.size()==0){//不存在的时候插入通知，并进行业务处理，否则是已经处理过，跳出
                        int reNoticet = shopChatDao.insertPayNotice(paymap);//插入支付通知
                        if(reNoticet!=0){//回填支付头、支付行、订单行的支付状态
                            Map payHmap = new HashMap();
                            payHmap.put("PAY_ZT", "Y");
                            payHmap.put("PAY_U_ID", pay_u_id);
                            payHmap.put("TRANSACTION_ID", transactionId);
                            payHmap.put("PAY_END_TIME", payTime);
                            payHmap.put("PAY_TYPE", trans_channel);
                            payHmap.put("OUT_TRANSNO", outTradeNo);// ylt平台生成的商品订单号
                            payHmap.put("PAY_TRANSNO", payTransNo);//在支付渠道中生产的商品订单号
                            shopChatDao.updatePayHeaderZT(payHmap);//

                            //修改订单头的支付状态和支付时间
                            Map orderHmap = new HashMap();
                            String B2B_ORDER_NUMBER=b2b_order_number;
                            orderHmap.put("B2B_ORDER_NUMBER", B2B_ORDER_NUMBER);
                            orderHmap.put("PAY_STATE", "Y");//支付状态该为已支付
                            orderHmap.put("SO_ZT", "7");//订单状态改为7
                            orderHmap.put("PAY_TIME", payTime);
                            orderHmap.put("ORDER_GXSJ", sysDate);
                            orderHmap.put("PAY_U_ID", pay_u_id);
                            orderHmap.put("PAY_TYPE",trans_channel);
                            weChatDao.updateOrderHPayZT(orderHmap);//回填更新订单头的支付状态

                            List payHList = shopChatDao.selectPayHByTransno(payHmap);
                            if (payHList != null && payHList.size() > 0) {
                                payHmap = (Map) payHList.get(0);
                                List payLList = shopChatDao.selectPayLByHID(payHmap);
                                if (payLList != null && payLList.size() > 0) {
                                    for (int i = 0; i < payLList.size(); i++) {
                                        Map payLmap=(Map) payLList.get(i);
                                        payLmap.put("TRANSACTION_ID", transactionId);
                                        payLmap.put("PAY_TRANSNO", payTransNo);
                                        payLmap.put("OUT_TRANSNO", outTradeNo);
                                        payLmap.put("PAY_END_TIME", payTime);
                                        payLmap.put("PAY_ZT", "Y");
                                        payLmap.put("PAY_U_ID", pay_u_id);
                                        shopChatDao.updatePayLineZT(payLmap);//更新支付行支付数据

                                        //更新发运行状态,
                                        Map orderLMap = new HashMap();
                                        orderLMap.put("DLV_LINE_ID", payLmap.get("DLV_LINE_ID"));
                                        orderLMap.put("PAY_TIME", payTime);
                                        orderLMap.put("PAY_STATE", "Y");
                                        weChatDao.updateDlvLinePayZT(orderLMap);//回填更新发运行的支付状态

                                    }
                                }
                            }

                        }
                    }
                }
            }
            return  "success";
        }catch(Exception ex) {
            log.error(ex.getMessage(),ex);
            return "fail";
        }
    }
    
    @ResponseBody
    @RequestMapping(value ="/notifyApplyCust",method= RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public String notifyApplyCust(@RequestBody String body) {
        try {
        	//partner=1201120792&remark=审批拒绝:多处信息不完整&subpartner=1201126981&type=insertcust&status=3
        	log.error("================="+body);
            try{
            	JSONObject jsonObject = JSON.parseObject(body);
            }catch(Exception ex) {
            	log.error(body, ex);
            }
            return  "success";
        }catch(Exception ex) {
            log.error(ex.getMessage(),ex);
            return "fail";
        }
    }
    
    //支付异步通知地址
    @Value("${pay.notify-url}")
    private String payNotifyUrl;
    //支付成功后页面回跳地址
    @Value("${pay.return-url}")
    private String payReturnUrl;
    //支付未完成时用户返回地址
    @Value("${pay.show-url}")
    private String payShowUrl;
    
    /**
     * 根据指定订单号，生成支付二维码，用于由业务员发起的收款动作
     * @param request 请求
     * @Param SHOP_CUST_ID 商业公司ID
     * @param B2B_ORDER_NUMBER 待支付的订单号
     * @param width 生成二维码的宽度
     * @Param height 生成二维码的高度
     */
    @ResponseBody
    @GetMapping(value="/getPayQrcode",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] getPayQrcode(HttpServletRequest request,
    		@RequestParam("SHOP_CUST_ID")String SHOP_CUST_ID,
    		@RequestParam("B2B_ORDER_NUMBER")String B2B_ORDER_NUMBER,
    		@RequestParam(name="width",defaultValue="250")int width,
    		@RequestParam(name="height",defaultValue="250")int height) {
    	if(StringUtils.isEmpty(SHOP_CUST_ID)) {
    		return null;
    	}
    	//查询商户信息，主要是为了拿到特约商户ID，用来调用支付接口
    	Map mchMap = new HashMap();
		mchMap.put("SHOP_CUST_ID", SHOP_CUST_ID);
		List listmch  = shopChatDao.selectMerchant(mchMap);//根据店铺id获取商户的信息；
		if(listmch==null || listmch.size()==0) {
			return null;
		}
		mchMap = (Map) listmch.get(0);
		String subpartner = mchMap.get("SUBPARTNER").toString();//商户号
		if(StringUtils.isEmpty(subpartner)) {
			return null;
		}
		//查询订单和发运信息
		mchMap.put("B2B_ORDER_NUMBER",B2B_ORDER_NUMBER);
		Map<String,Object> payInfo = weChatService.selectOrderPayInfo(mchMap);
		if(payInfo==null) {
			return null;
		}
		String U_ID = payInfo.get("U_ID").toString();
		String totalFee = payInfo.get("HJ_JE").toString();
		
		String notify_url = payNotifyUrl;//异步通知路径
		String return_url = payReturnUrl+B2B_ORDER_NUMBER;//同步通知路径
		String show_url = payShowUrl+B2B_ORDER_NUMBER;//商户展示路径
		String ip=YltUtils.getIpAddr(request);
		if(ip!=null) {
			ip=ip.split(",")[0];//多个ip取第一个
		}else {
			ip="127.0.0.1";
		}
    	Kv params = Kv.create()
			.set("subpartner", subpartner)//特约商户号
			.set("totalFee", totalFee)//订单总金额，人民币，单位元，可包含两位小数
			.setIfNotBlank("remark", "")
			//返回类型，0-二维码图片流，1-为URL，默认为0
			//如果为0，则由银行返回支付二维码图片的base64格式字符串，需要我们转为图片
			//不过经过测试发现，该二维码图片的内容，其实就相当于qrReturnType传入1时所返回的二维码URL串
			.setIfNotBlank("qrReturnType", "1")
			.set("subject", "订单编号"+B2B_ORDER_NUMBER)
			.set("body", "订单编号"+B2B_ORDER_NUMBER)
			.set("outTradeNo", B2B_ORDER_NUMBER)
			.set("spbillCreateIp", ip)
			.setIfNotBlank("notifyUrl", notify_url)//异步通知路径
			.setIfNotBlank("returnUrl", return_url)//同步通知路径
			.setIfNotBlank("attach", SHOP_CUST_ID + "|" + B2B_ORDER_NUMBER + "|" + U_ID)
			.setIfNotBlank("deviceInfo", "");
    	Kv result = com.utils.tfzf.Api.dynamicPayPreCreate(params);
    	if(result.getBoolean("status")) {
    		//接口返回
    		String qrcodeImg = result.getStr("qrCode");
    		//生成二维码
    		QrConfig config = new QrConfig(width, height);
            config.setErrorCorrection(ErrorCorrectionLevel.H);// 高纠错级别
    		return QrCodeUtil.generatePng(qrcodeImg, config);
    	}
    	return null;
    }
    /**
     * 提现结果异步通知处理<br/>
     * @param request HttpServletRequest实例
     */
    @ResponseBody
    @RequestMapping("/notifyUrl_tx")
    public String notifyUrl_tx(HttpServletRequest request) {
        try {
            //提现返回的是json串，再转换为string，
            request.setCharacterEncoding("utf-8");
            BufferedReader br = request.getReader();
            String line="";
            StringBuffer sb=new StringBuffer();
            while((line = br.readLine()) != null){
                sb.append(line);
            }
            String content = new String(sb.toString().getBytes("ISO8859-1"),"UTF-8");
            log.debug("收到提现异步通知，内容：" + content);
            if(StringUtils.isEmpty(content)||!JSONUtil.isJson(content)) {
                return "fail";
            }
            JSONObject jsonObject = JSON.parseObject(content);
            String tx_state=jsonObject.getString("status");//交易状态：0待受理，1处理中，2成功，5失败
            if("2".equals(tx_state)){
                String   subpartner=jsonObject.getString("subpartner");//特约商户号
                String   transactionId=jsonObject.getString("transactionId");//提现流水号
                String   charge=jsonObject.getString("charge");//提现流水号
                //根据提现流水号调用提现查询接口查询银行提现单
                Kv params = Kv.create()
                        .set("subpartner", subpartner)//特约商户号
                        .set("transactionId",transactionId);//商户订单号
                Kv result=com.utils.tfzf.Api.withdrawQuery(params);
                if(result.getBoolean("status")){
                    String transAmount=result.getStr("transAmount");//提现金额
                    String transState=result.getStr("transState");//交易状态 0-待受理 1-处理中 2-成功 5-失败

                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
                    Date sysDate = new Date();
                    String nowDate=df.format(sysDate);
                    Map WithdrawHmap = new HashMap();
                    WithdrawHmap.put("TRANSACTION_ID",transactionId);
                    WithdrawHmap.put("SUBPARTNER", subpartner);//特约商户号
                    WithdrawHmap.put("TRANS_AMOUNT", transAmount);//提现金额
                    WithdrawHmap.put("TRADE_STATE", transState);
                    WithdrawHmap.put("CHARGE",charge);
                    Timestamp   txsjTime= Timestamp.valueOf(nowDate);
                    WithdrawHmap.put("TXSJ",txsjTime);
                    shopChatDao.updateWithdrawZT(WithdrawHmap);//
                }
            }
            return  "success";
        }catch(Exception ex) {
            log.error(ex.getMessage(),ex);
            return "fail";
        }

    }
}
